package com.example.my_bookkeeping.ui.bookkeep;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.my_bookkeeping.R;
import com.example.my_bookkeeping.callback.SwitchViewPager;
import com.example.my_bookkeeping.data.manager.Manager;
import com.example.my_bookkeeping.data.manager.BookKeepManager;
import com.example.my_bookkeeping.data.manager.CategoryManager;
import com.example.my_bookkeeping.data.user.BookKeep;

import java.util.ArrayList;
import java.util.List;

public class BookkeepFragment extends Fragment implements Manager.Observer {
    private SwitchViewPager switchViewPager;
    private RecordAdapter adapter;
    private CategorySpinnerAdapter categoryAdapter;
    private Spinner categorySpinner;

    private final BookKeepManager bookKeepManager = BookKeepManager.getInstance();
    private final CategoryManager categoryManager = CategoryManager.getInstance();
    private BookKeepType currentType = BookKeepType.ALL;
    private String currentCategory = "全部";

    private enum BookKeepType {
        ALL,
        INCOME,
        EXPENSE
    }

    // 设置RecordAdapter
    public class RecordAdapter extends RecyclerView.Adapter<RecordAdapter.RecordViewHolder> {

        @NonNull
        @Override
        public RecordViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_record, parent, false);
            return new RecordViewHolder(view);
        }

        private final List<BookKeep> data = new ArrayList<>();

        @SuppressLint("NotifyDataSetChanged")
        public void setData(List<BookKeep> newData) {
            data.clear();
            data.addAll(newData);
            notifyDataSetChanged();
        }

        @Override
        public int getItemCount() {
            return data.size();
        }

        @Override
        public void onBindViewHolder(RecordViewHolder holder, int position) {
            BookKeep item = data.get(position);
            holder.itemView.setTag(holder);  // 设置tag以便获取position
            holder.tvTime.setText(item.getTime());
            holder.tvAmount.setText(String.valueOf(item.getAmount()));
            holder.tvCategory.setText(item.getCategory());
            holder.tvType.setText(item.getIsIncome() ? getString(R.string.book_keep_label_income) : getString(R.string.book_keep_label_expense));
            holder.tvRemark.setText(item.getRemark());

            // 长按弹出菜单
            holder.itemView.setOnLongClickListener(view -> {
                showPopupMenu(view, position);
                return true;
            });
        }

        // 这里设置每个item的显示样式，已经实现了视图资源的绑定
        public class RecordViewHolder extends RecyclerView.ViewHolder {
            TextView tvTime, tvAmount, tvType, tvCategory, tvRemark;

            public RecordViewHolder(View itemView) {
                super(itemView);
                tvTime = itemView.findViewById(R.id.tv_time);
                tvAmount = itemView.findViewById(R.id.tv_amount);
                tvType = itemView.findViewById(R.id.tv_type);
                tvCategory = itemView.findViewById(R.id.tv_category);
                tvRemark = itemView.findViewById(R.id.tv_remark);
            }
        }
    }

    public void showPopupMenu(View view, int position) {
        PopupMenu popupMenu = new PopupMenu(requireContext(), view);
        MenuInflater inflater = popupMenu.getMenuInflater();
        inflater.inflate(R.menu.menu_book_keep_change, popupMenu.getMenu());

        popupMenu.setOnMenuItemClickListener(item -> {
            if (item.getItemId() == R.id.menu_item_delete) {
                bookKeepManager.delete(adapter.data.get(position));
                return true;
            } else if (item.getItemId() == R.id.menu_item_edit) {
                showEditDialog(adapter.data.get(position));
                return true;
            }
            return false;
        });
        popupMenu.show();
    }

    private void showEditDialog(BookKeep bookKeep) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_edit_bookkeep, null);

        EditText etAmount = dialogView.findViewById(R.id.et_amount);
        EditText etCategory = dialogView.findViewById(R.id.et_category);
        EditText etRemark = dialogView.findViewById(R.id.et_remark);

        // 设置当前值
        etAmount.setText(String.valueOf(bookKeep.getAmount()));
        etCategory.setText(bookKeep.getCategory());
        etRemark.setText(bookKeep.getRemark());

        builder.setView(dialogView)
                .setTitle(R.string.book_keep_dialog_title_edit)
                .setPositiveButton(R.string.book_keep_dialog_button_confirm, (dialog, which) -> {
                    String amountStr = etAmount.getText().toString();
                    String category = etCategory.getText().toString();
                    String remark = etRemark.getText().toString();

                    if (TextUtils.isEmpty(amountStr) || TextUtils.isEmpty(category)) {
                        Toast.makeText(requireContext(), R.string.book_keep_error_empty_fields, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    try {
                        double amount = Double.parseDouble(amountStr);
                        // 调用UserDataStore的新方法更新账目字段
                        bookKeepManager.update(
                                bookKeep.getId(),
                                amount,
                                category,
                                remark
                        );
                    } catch (NumberFormatException e) {
                        Toast.makeText(requireContext(), R.string.book_keep_error_invalid_amount, Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton(R.string.book_keep_dialog_button_cancel, null)
                .show();
    }

    private void switchBookKeepType(int checkedId) {
        if (checkedId == R.id.radioButton_income) {
            currentType = BookKeepType.INCOME;
        } else if (checkedId == R.id.radioButton_expense) {
            currentType = BookKeepType.EXPENSE;
        } else {
            currentType = BookKeepType.ALL;
        }
        categorySpinner.setSelection(0);
        update();
    }

    public void update() {
        if(currentCategory.equals("全部")) {
            switch (currentType) {
                case EXPENSE:
                    adapter.setData(bookKeepManager.searchBookKeep(bookKeep -> !bookKeep.getIsIncome()));
                    categoryAdapter.setCategories(categoryManager.getExpenseCategoryList());
                    break;
                case INCOME:
                    adapter.setData(bookKeepManager.searchBookKeep(BookKeep::getIsIncome));
                    categoryAdapter.setCategories(categoryManager.getIncomeCategoryList());
                    break;
                default:
                    adapter.setData(bookKeepManager.getAll());
                    categoryAdapter.setCategories(categoryManager.getAllCategoryList());
                    break;
            }
        } else {
            adapter.setData(bookKeepManager.searchBookKeep(
                    bookKeep -> bookKeep.getCategory().equals(currentCategory)));
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        bookKeepManager.removeObserver(this);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_bookkeep, container, false);

        // 初始化 RecyclerView
        RecyclerView recyclerView = rootView.findViewById(R.id.recyclerView_record);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new RecordAdapter();
        recyclerView.setAdapter(adapter);

        // 跳转到分类页面
        if (getActivity() instanceof SwitchViewPager) {
            switchViewPager = (SwitchViewPager) getActivity();
        }
        rootView.findViewById(R.id.button_to_category)
                .setOnClickListener(view -> switchViewPager.switchViewPager(1));

        // 初始化category spinner（改为成员变量）
        categoryAdapter = new CategorySpinnerAdapter(categoryManager.getAllCategoryList());
        categorySpinner = rootView.findViewById(R.id.spinner_category); // 赋值给成员变量
        categorySpinner.setAdapter(categoryAdapter);

        // 设置显示收支类型的radio group
        ((RadioGroup)rootView.findViewById(R.id.radioGroup_type))
                .setOnCheckedChangeListener((group, checkedId) -> switchBookKeepType(checkedId));

        // 设置spinner项的点击事件，切换显示分类
        categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                currentCategory = (String) parent.getItemAtPosition(position);
                update();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent){ }
        });

        bookKeepManager.addObserver(this);

        return rootView;
    }

    // 新增：每次Fragment可见时重新初始化spinner
    @Override
    public void onResume() {
        super.onResume();
        if (categorySpinner == null || categoryAdapter == null || categoryManager == null) {
            return; // 防止空指针
        }
        update();
    }

    private class CategorySpinnerAdapter extends ArrayAdapter<String> {
        public CategorySpinnerAdapter(ArrayList<String> _categories) {
            super(requireContext(), android.R.layout.simple_spinner_item, _categories);
            insert("全部",0);
        }
        public void setCategories(ArrayList<String> categories) {
            clear();
            add("全部");
            addAll(categories);
            notifyDataSetChanged();
        }
    }
}